/*******************************************************************************
 * $Header$
 * $Revision$
 * $Date$
 *
 *==============================================================================
 *
 * Copyright©hxlife/hulife 
 * All rights reserved.
 * 
 * Created on 2018年5月31日
 *******************************************************************************/

package com.hualife.md.member.service.impl;

import java.util.Properties;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hualife.md.common.service.IKvQueryService;
import com.hualife.md.member.dao.mybatis.entity.MemberInfo;
import com.hualife.md.member.service.IMemberManageService;
import com.hualife.support.exception.BusinessException;
import com.hualife.support.exception.SysException;

/**
 * @description: TODO 此处填写 class 信息
 * @author 孙小冬 (mailto:sunxiaodong001@hualife.cc)
 */
@Service("memberManageService")
public class MemberManageServiceImpl implements IMemberManageService {
	private static final Logger logger = LoggerFactory
			.getLogger(MemberManageServiceImpl.class);

	@Autowired
	private IKvQueryService kvQueryService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.hualife.md.member.service.IMemberManageService#login(java.lang.String
	 * , java.lang.String)
	 */
	@Override
	public MemberInfo login(String memberId, String password) {
		if(memberId == null || password == null || "".equals(memberId.trim())||"".equals(password.trim()))
			throw new BusinessException("用户名或密码不能为空!");

		Properties env = new Properties();
		String ip = kvQueryService.getValue("ad.ip");
		String port = kvQueryService.getValue("ad.port");
		String domain = kvQueryService.getValue("ad.domain");
		String searchBase = kvQueryService.getValue("ad.search.base");
		String searchFilter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName="+memberId+"))";

		String ldapURL = "LDAP://" + ip + ":" + port;// ip:port
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.SECURITY_AUTHENTICATION, "simple");// "none","simple","strong"
		env.put(Context.SECURITY_PRINCIPAL, memberId + domain);
		env.put(Context.SECURITY_CREDENTIALS, password);
		env.put(Context.PROVIDER_URL, ldapURL);
		LdapContext ctx = null;
		MemberInfo memberInfo = new MemberInfo();
		memberInfo.setMemberId(memberId);
		try {
			ctx = new InitialLdapContext(env, null);// 初始化上下文
			SearchControls searchCtls = new SearchControls();
			searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			searchCtls.setReturningAttributes(new String[]{"name"});
			NamingEnumeration<SearchResult> answer = ctx.search(searchBase,
					searchFilter, searchCtls);
			while (answer.hasMoreElements()) {
				SearchResult sr = (SearchResult) answer.next();

				Attributes Attrs = sr.getAttributes();
				if (Attrs != null) {
					try {
						for (NamingEnumeration<? extends Attribute> ne = Attrs
								.getAll(); ne.hasMore();) {
							Attribute Attr = (Attribute) ne.next();

							String attributeID = Attr.getID().toString();

							if ("name".equals(attributeID)) {
								NamingEnumeration<?> e = Attr.getAll();
								memberInfo.setMemberName(e.next().toString());
							}

						}
					} catch (NamingException e) {
						logger.error("Throw Exception : " + e);
					}}}
			
			logger.info("用户{}身份验证成功!", memberId);
			return memberInfo;
		} catch (AuthenticationException e) {
			logger.info("用户{}身份验证失败!", memberId);
			throw new BusinessException("用户名或密码错误!");
		} catch (javax.naming.CommunicationException e) {
			logger.error("AD域连接失败!");
			e.printStackTrace();
			throw new SysException("AD域连接失败!");
		} catch (Exception e) {
			logger.error("身份验证未知异常!");
			e.printStackTrace();
			throw new SysException("身份验证未知异常!");
		} finally {
			if (null != ctx) {
				try {
					ctx.close();
					ctx = null;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

}

/*
 * 修改历史 $Log$
 */